package com.ruoyi.server.read;

import com.ruoyi.server.enums.*;
import com.ruoyi.server.pkg.SendMsg;
import com.ruoyi.server.utils.OnlineUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.time.LocalDateTime;


/**
 *  中央控制器, 这里的Read0并不是一个很好的决策
 *
 *
 * @author OpenACloud
 */
public abstract class BaseCenterReader extends SimpleChannelInboundHandler<SendMsg> implements BasePullReader{

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, SendMsg sendMsg)  {
        switch (sendMsg.CMD) {
            case AddConstants5.ADD_FRIEND:
            case AddConstants5.ADD_GROUP:
                sendMsg.getReader().addFriendOrGroup(ctx, sendMsg);
                break;
            case AddConstants5.AP_ADD_FRIEND:
            case AddConstants5.AP_ADD_GROUP:
                sendMsg.getReader().apFriendOrGroupProcessing(ctx, sendMsg);
                break;
            case CmdConstants.PRIVATE_CMD:
            case CmdConstants.GROUP_CMD:
                sendMsg.getReader().sendFriendOrGroupMsg(ctx, sendMsg);
                break;
            case DeleteConstants6.DELETE_FRIEND:
            case DeleteConstants6.DELETE_GROUP:
                sendMsg.getReader().deleteFriendOrGroup(ctx, sendMsg);
                break;
            case PullConstants3.PULL_MESSAGES:
                sendMsg.getReader().pullMessages(ctx, ctx.attr(OnlineUtil.PASSAGE_WAR_USER).get());
                break;
        }
    }


//    @Override
//    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
//        this.resourceRelease(ctx);
//    }
//
//    @Override
//    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//        this.resourceRelease(ctx);
//    }
//
//    private void resourceRelease(ChannelHandlerContext ctx){
//        Long userId = ctx.attr(OnlineUtil.SEND_ID).get();
//        OnlineUtil.ONLINE_MAPS.remove(userId);
//
//        SendMsg sendMsg = new SendMsg();
//        sendMsg.CMD = GoLiveConstants2.OFFLINE;
//        sendMsg.STATUS = GoLiveConstants2.OFFLINE_STATUS;
//        sendMsg.SENDID = -1L;
//        sendMsg.CONTEXT = "SYSTEM OFFLINE";
//        sendMsg.TIME = LocalDateTime.now();
//        ctx.channel().writeAndFlush(sendMsg);
//    }


    protected abstract void sendFriendOrGroupMsg(ChannelHandlerContext ctx, SendMsg sendMsg);
    protected abstract void deleteFriendOrGroup(ChannelHandlerContext ctx, SendMsg sendMsg);

    protected abstract void addFriendOrGroup(ChannelHandlerContext ctx, SendMsg sendMsg);
    protected abstract void apFriendOrGroupProcessing(ChannelHandlerContext ctx, SendMsg sendMsg);
}